package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.bean.InteralGoodsdesc;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 商品详情
 * 
 * @author Administrator
 * 
 */
public class ChangeDescActivity extends BaseActivity {


    private ScheduledExecutorService scheduledExecutor;
    private TextView vMoreNiu, vNiuniu;
    private ListView vChangelist;


    private List<String> imageViewUrlLists;
    private RollViewPager mRollViewPager;
    private ViewPager vViewpager;
    private TextView vTitle, vJinbi, vNum, vIntegral;
    private WebView webView;

    private ArrayList<View> dotLists;
    // 轮播
    private RollViewPager rollViewPager;
    private RelativeLayout viewpager;
    private LinearLayout vViewpage;
    private TextView vDescription;
    private LinearLayout vDotall;

    InteralGoodsdesc goods = null;

    private int lastPointIndex = 0;
    private int currentItem = 0;
    private int mWidth;

    @Override
    protected int getContentViewResId() {
        return R.layout.fragment_change_desc;
    }

    @Override
    protected void initViews() {
        super.initViews();

        mWidth = CommonParameter.sScreenWidth * 2 / 3;

        setTopBarTitle("商品详情");
        // 牛牛币
        vNiuniu = (TextView) findViewById(R.id.niuniubi);
        mRmb = (ImageView) findViewById(R.id.rmb);
        showniuniu();
        vViewpager = (ViewPager) findViewById(R.id.top_change_viewpager);

        vViewpager.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, mWidth));

        vDotall = (LinearLayout) findViewById(R.id.ll_points1);
        vTitle = (TextView) findViewById(R.id.title);// 标题
        vJinbi = (TextView) findViewById(R.id.tv_jinbi);
        vNum = (TextView) findViewById(R.id.tv_num);
        vIntegral = (TextView) findViewById(R.id.tv_integral);
        webView = (WebView) findViewById(R.id.wv);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");

        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new MyPagerTask(), 2, 3, TimeUnit.SECONDS);
        initdata();


    }

    @Override
    protected void initEvents() {
        super.initEvents();


        vViewpager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                int myIndex = position % goods.img_url.size();
                // 将当前指示点的图片enable设为true
                if (vDotall.getChildAt(myIndex) != null)
                    vDotall.getChildAt(myIndex).setEnabled(true);
                // 将上一个指示点设置为false
                if (vDotall.getChildAt(lastPointIndex) != null)
                    vDotall.getChildAt(lastPointIndex).setEnabled(false);
                lastPointIndex = myIndex;

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        vIntegral.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (UserState.isLogged(ChangeDescActivity.this)) {
                    /*
                     * Intent intent = new Intent(ChangeDescActivity.this, MainActivity.class);
                     * intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                     * ChangeQueRenFragment.class.getCanonicalName()); Bundle bundle = new Bundle();
                     * bundle.putString("ex_id", getIntent().getStringExtra("ex_id"));
                     * intent.putExtra(Constants.KEY_BUNDLE, bundle);
                     * ChangeDescActivity.this.startActivity(intent);
                     */
                    // startFragment(new ChangeQueRenFragment(), bundle);
                    int niuniu = 0;
                    int exchange_integral = 0;
                    try {
                        niuniu = Integer.parseInt(UserState.getUser().niuniu);
                        exchange_integral = Integer.parseInt(goods.exchange_integral);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    if (niuniu >= exchange_integral) {
                        Intent intent =
                                new Intent(ChangeDescActivity.this, ChangeQueRenActivity.class);
                        intent.putExtra("ex_id", getIntent().getStringExtra("ex_id"));
                        intent.putExtra("pro_jinbibi", goods.exchange_integral);
                        startActivityForResult(intent, 0);
                    } else {
                        Toast.makeText(getApplication(), "您尾巴币数不足，暂时不能兑换", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }
        });

    }

    private void showniuniu() {
        if (UserState.getUser() != null) {
            vNiuniu.setText(UserState.getUser().niuniu + "尾巴币");
        } else {
            mRmb.setVisibility(View.INVISIBLE);
            vNiuniu.setVisibility(View.INVISIBLE);
        }
    }

    private void initdata() {
        // String exid = "3";
        if (null != getIntent()) {
            String exid = getIntent().getStringExtra("ex_id");
            getMoccaApi().getChangeDesc(exid, new IRequest<InteralGoodsdesc>() {

                @Override
                public void request(InteralGoodsdesc t) {
                    if (null != t) {
                        goods = t;
                        webView.loadData(goods.goods_desc, "text/html; charset=UTF-8", null);

                        vViewpager.setAdapter(new MyPagerAdapter(goods.img_url));
                        initDots(goods.img_url.size());
                        vTitle.setText(goods.goods_name);
                        vJinbi.setText(goods.exchange_integral + "尾巴币");
                        vNum.setText(goods.goods_number);
                    }
                }

            });
        }

    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        vDotall.removeAllViews();
        for (int i = 0; i < size; i++) {
            // LinearLayout.LayoutParams layoutParams =
            // new LinearLayout.LayoutParams(CommonUtil.dip2px(mActivity, 10),
            // CommonUtil.dip2px(mActivity, 10));
            // layoutParams.setMargins(5, 0, 5, 0);
            // // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // // 15);
            //
            // // lp.leftMargin = 10;
            //
            // View m = new View(mActivity);
            // if (i == 0) {
            // m.setBackgroundResource(R.drawable.point_enable);
            // } else {
            // m.setBackgroundResource(R.drawable.point_normal);
            // }
            // m.setLayoutParams(layoutParams);
            // dotLists.add(m);
            // vDotall.addView(m);

            // 添加指示点
            ImageView point = new ImageView(getApplicationContext());
            point.setBackgroundResource(R.drawable.point_background);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, -2);
            params.leftMargin = 15;
            point.setLayoutParams(params);

            vDotall.addView(point);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }

        }
    }

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
    }


    private class MyPagerTask implements Runnable {

        @Override
        public void run() {
            // 切换图片
            currentItem = currentItem + 1;
            handler.sendEmptyMessage(0);
        }
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {

            // 指定当前页面
            vViewpager.setCurrentItem(currentItem);
        };
    };
    private ImageView mRmb;

    @Override
    public void onResume() {
        super.onResume();
        showniuniu();
    }


    class MyPagerAdapter extends PagerAdapter {

        List<String> list;

        public MyPagerAdapter(List<String> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 获得指定位置的view
            ImageView iv = new ImageView(ChangeDescActivity.this);
            LayoutParams params = new LinearLayout.LayoutParams(mWidth, mWidth);
            params.gravity = Gravity.CENTER;
            iv.setLayoutParams(params);
            // iv.setScaleType(ScaleType.FIT_XY);
            if (list != null) {
                ImageLoader.getInstance().displayImage(list.get(position % list.size()), iv);
            }
            // 将view 添加至container
            container.addView(iv);
            return iv;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            this.setResult(1);
            finish();
        }
    }

}
